#!/bin/sh

### BEGIN INIT INFO
# Provides:          anybackupserver
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts the anybackupserver daemon.
### END INIT INFO

### For CentOS
# chkconfig:         2345 20 80
# description:       Starts the anybackupserver daemon.

if [ -f /etc/rc.d/init.d/functions ]; then
	. /etc/rc.d/init.d/functions
fi

if [ -f /lib/lsb/init-functions ]; then
	. /lib/lsb/init-functions
fi

DAEMON="anybackupserver"
PIDFILE="/var/run/anybackupserver.pid"
COMMAND="$1"

status () {
	PID=`cat $PIDFILE 2> /dev/null`
	if [ -f $PIDFILE -a "`ps ax | grep \"^ *$PID.*$DAEMON.py\" | grep -v grep | wc -l`" -eq "1" ]; then
		[ "$COMMAND" = "status" ] && echo "$DAEMON is running."
		return 0
	else
		[ "$COMMAND" = "status" ] && echo "$DAEMON isn't running."
		return 1
	fi
}

daemon_start () {
	nice -n 1 $DAEMON.py > /dev/null &
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		ps ax | grep "$DAEMON.py" | grep -v grep | tail -1 | awk '{print $1}' > $PIDFILE
	fi
	return $RETVAL
}

start () {
    export LANG="en_US.UTF-8"
	echo -n "Starting $DAEMON ... "
	status && echo "$DAEMON already running." && return 0
	if [ -f /sbin/start-stop-daemon ]; then
		start-stop-daemon --start --pidfile $PIDFILE --exec /usr/bin/python --nicelevel 1 --background -- /usr/bin/$DAEMON.py
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			echo "OK"
		else
			echo "FAILED"
		fi
	else
		daemon +5 --check $DAEMON $0 daemon_start
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			success $"$base startup"
		else
			failure $"$base startup"
		fi
		echo
	fi
	sleep 1 # Allow some time for the daemon to appear in the processes list
	[ $RETVAL -eq 0 ] && ps ax | grep "$DAEMON.py" | grep -v grep | tail -1 | awk '{print $1}' > $PIDFILE
	return $RETVAL
}

stop () {
	echo -n "Shutting down $DAEMON ... "
	if [ -f /sbin/start-stop-daemon ]; then
		start-stop-daemon --stop --quiet --retry=TERM/10/KILL/5 --pidfile $PIDFILE --exec /usr/bin/python
		RETVAL=$?
		[ $RETVAL -eq 0 ] && echo "OK" || echo "FAILED"
	else
		killproc $DAEMON
		RETVAL=$?
		[ $RETVAL -eq 0 ] && success $"$base shutdown" || failure $"$base shutdown"
		echo
	fi
	[ $RETVAL -eq 0 ] && rm -f $PIDFILE
	return $ret
}

restart () {
	stop
	sleep 1
	start
}

condrestart () {
	status && restart || :
}

case "$COMMAND" in
	status)
		status
		;;
	start)
		start
		;;
	daemon_start)
		daemon_start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	force-reload)
		restart
		;;
	condrestart)
		condrestart
		;;
	*)
		echo $"Usage: $0 {start|stop|status|condrestart|restart}"
		exit 1
		;;
esac

exit $?
